package com.brspace.qualitycontrol.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.brspace.qualitycontrol.controller.admin.FileController;
import com.brspace.qualitycontrol.entity.PublishFile;
import com.brspace.qualitycontrol.entity.wps.entity.WFileT;
import com.brspace.qualitycontrol.service.FileService;
import com.brspace.qualitycontrol.service.FileTService;
import com.brspace.qualitycontrol.service.PublishFileService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import static java.lang.System.out;

@Component
public class WordUtils {


    private static FileService fileService;

    private static PublishFileService publishFileService;

    private static FileTService fileTService;

    @Autowired
    public WordUtils (FileService fileService, PublishFileService publishFileService, FileTService fileTService) {
        WordUtils.fileService = fileService;
        WordUtils.publishFileService = publishFileService;
        WordUtils.fileTService = fileTService;
    }


    //配置信息,代码本身写的还是很可读的,就不过多注解了
    private static Configuration configuration = null;
    //这里注意的是利用WordUtils的类加载器动态获得模板文件的位置
    private static final String templateFolder =  WordUtils.class.getClassLoader().getResource("").getPath();  //"D:/patrol";//
    //private static final String templateFolder = "H:/我的项目/lm/lm/web/src/main/webapp/WEB-INF/templates";
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private WordUtils() {
        throw new AssertionError();
    }

    public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,String title,String ftlFile) throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(ftlFile);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        String fileName = title + ".doc";
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map,freemarkerTemplate,title);
            fin = new FileInputStream(file);
            // 将生成的word文档上传阿里云并保存到数据库
            String upload = fileService.upload2(file, title, fileName);
            PublishFile publishFile = new PublishFile();
            publishFile.setPId((String) map.get("id"));
            publishFile.setFile(upload);
            publishFile.setFileName(fileName);
            publishFile.setFileType(1);
            publishFileService.save(publishFile);
//			response.setCharacterEncoding("utf-8");
//            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
//            // 设置浏览器以下载的方式处理该文件名
//			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//
//            out = response.getOutputStream();
//            byte[] buffer = new byte[512];  // 缓冲区
//            int bytesToRead = -1;
//            // 通过循环将读入的Word文件的内容输出到浏览器中
//            while((bytesToRead = fin.read(buffer)) != -1) {
//                out.write(buffer, 0, bytesToRead);
//            }
//            out.flush();
        } finally {
            if(fin != null) fin.close();
            if(out != null) out.close();
            if(file != null) file.delete(); // 删除临时文件
        }
    }

    public static String exportMillCertificateWord( Map map,String title,String ftlFile,String userId) throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(ftlFile);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        String fileName = title + ".doc";
        try {
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map,freemarkerTemplate,title);
            fin = new FileInputStream(file);
            // 将生成的word文档上传阿里云并保存到数据库
            String upload = fileService.upload2(file, title, fileName);
            PublishFile publishFile = new PublishFile();
            publishFile.setPId((String) map.get("id"));
            publishFile.setFile(upload);
            publishFile.setFileName(fileName);
            publishFile.setFileType(1);
            int size = (int) file.length();
            Date date = new Date();
            long dataTime = date.getTime();
            WFileT f = new WFileT(fileName, 1, size, userId, userId, dataTime, dataTime, upload);
            fileTService.save(f);
            publishFile.setWId(f.getId());
            publishFileService.save(publishFile);
            return f.getId();
//			response.setCharacterEncoding("utf-8");
//            response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
//            // 设置浏览器以下载的方式处理该文件名
//			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//
//            out = response.getOutputStream();
//            byte[] buffer = new byte[512];  // 缓冲区
//            int bytesToRead = -1;
//            // 通过循环将读入的Word文件的内容输出到浏览器中
//            while((bytesToRead = fin.read(buffer)) != -1) {
//                out.write(buffer, 0, bytesToRead);
//            }
//            out.flush();
        } finally {
            if(fin != null) fin.close();
            if(out != null) out.close();
            if(file != null) file.delete(); // 删除临时文件
        }
    }

    private static File createDoc(Map<?, ?> dataMap, Template template, String title) {
        String name =  title + ".doc";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}
